package app.circlerequest;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import app.utils.DBDataGetterJDBCSiotwx;
import com.meter.data.DBDataGetter;

public class MeterReadRecordInTime {
	private float time=0.5F;
	public float getTime() {
		return time;
	}

	public void setTime(float time) {
		this.time = time;
	}

	public void getMeterReadRecord() {
		
		getRecord();
	}

	// 执行定期获取记录
	private void getRecord() {
//		Timer timer = new Timer();
//		// 添加定期执行任务（定期获取最新读表记录）
//		timer.schedule(new TimerTask() {
//
//			@Override
//			public void run() {
//				System.out.println("\n#############远程抄表执行了更新数据#############\n");
//				System.out.println((long)(time * 3600 * 1000));
//				//获取最新读表数据
//				List<Map<String,String>> meterLastRead = getMeterLastRead();
//				//将数据更新进数据库
//				upadteMeterLastRead(meterLastRead);
//			}
//
//		}, 1000L,(long)(time * 3600 * 1000));
	}

	// 将数据更新进数据库
	private void upadteMeterLastRead(List<Map<String,String>> meterLastReads) {
		
		//DBDataGetterJDBCSiotwx.executeSqlWithoutResult();
		//将要添加的数据格式化成要执行的sql语句
		StringBuilder sqls=new StringBuilder();
		for(Map<String, String> entity:meterLastReads){
			sqls.append(mapToJdbcSql(entity));
		}
		DBDataGetterJDBCSiotwx.executeSqlWithoutResult(sqls.toString());
	}
	// 将要添加的数据格式化成要执行的sql语句
	private String mapToJdbcSql(Map<String, String> entity) {
		String sql = "replace into read_meter(:key) values (:value);";
		StringBuilder buildKey=new StringBuilder();
		StringBuilder buildvalue=new StringBuilder();
		for(Map.Entry<String, String> entry:entity.entrySet()){
			buildKey.append("`");
			buildKey.append(entry.getKey());
			buildKey.append("`,");
			buildvalue.append("'");
			buildvalue.append(entry.getValue()==null?"":entry.getValue());
			buildvalue.append("',");
			
		}
		
		return sql.replace(":key", buildKey.deleteCharAt(buildKey.length()-1))
				.replace(":value", buildvalue.deleteCharAt(buildvalue.length()-1));
	}

	// 获取最新的读表记录
	private List<Map<String, String>> getMeterLastRead() {
		// 暂时储存匹配结果
		List<Map<String, String>> temp = new ArrayList<>();

		// 获取所有的电表编号
		String sqlMeter = "SELECT ID DBMeterKID ,[No] KNum,ColectorNo DBCollectorNum,Location KLocation FROM HD_Meter";
		List<HashMap<String, String>> meters = DBDataGetter.executeSqlWithResult(sqlMeter);

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String date = format.format(new Date(System.currentTimeMillis() - 1000L * 3600 * 24 * 10));

		// 获取全部读表记录
		String sql = "SELECT " + "HD_ReadMeter.MeterID  DBMeterKID, " + "HD_Meter.ColectorNo DBCollectorNum, "
				+ "HD_Meter.Location KLocation, " + "HD_ReadMeter.MeterNo KNum, "
				+ "HD_ReadMeter.ThisRead KThisTimeRead, " + "HD_ReadMeter.ReadTime KReadTime " + "FROM  "
				+ "HD_ReadMeter LEFT JOIN HD_Meter ON HD_ReadMeter.MeterID=HD_Meter.ID "
				+ " where HD_ReadMeter.ReadTime>=" + date + "ORDER BY HD_ReadMeter.ReadTime desc";
		List<HashMap<String, String>> readHis = DBDataGetter.executeSqlWithResult(sql);

		// 获取当前电表的最新读表数据
		for (Map<String, String> meter : meters) {
			for (Map<String, String> his : readHis) {
				if (meter.get("DBMeterKID").equals(his.get("DBMeterKID"))) {
					temp.add(his);
					break;
				}
			}
		}

		// 处理时间格式
		for (int i = 0; i < temp.size(); i++) {
			String KReadTime = temp.get(i).get("KReadTime");
			int pos = KReadTime.lastIndexOf(":");
			KReadTime = KReadTime.substring(0, pos);
			temp.get(i).put("KReadTime", KReadTime);
		}

		// 添加没有的表
		for (HashMap<String, String> en : meters) {
			if (!isTheOne(temp, en)) {
				temp.add(en);
			}
		}

		temp.sort((o1, o2) -> {
			Integer v1 = Integer.valueOf(o1.get("DBCollectorNum"));
			Integer v2 = Integer.valueOf(o2.get("DBCollectorNum"));
			return v1 - v2;
		});
		
		return temp;
	}

	private boolean isTheOne(List<Map<String, String>> temp,Map<String, String> thisOne){
		for(Map<String, String> entry:temp){
			if (thisOne.get("DBMeterKID").equals(entry.get("DBMeterKID"))) {
				return true;
			}
		}
		
		return false;
	}
	
}
